﻿using System;
using System.Linq;
using System.Web;
using Nydus.Model.Entities;
using Nydus.Model.Repositories;
using Nydus.Model.Interfaces;
using Nydus.WebForms.Frontend.ViewModels;
using Nydus.WebForms.Frontend.Views;
using Nydus.WebForms.FrontendModel;

namespace Nydus.WebForms.Frontend.Presenters
{
    public class SelectCustomerPresenter : BasePresenter<SelectCustomerViewModel, ISelectCustomerView>
    {
        public SelectCustomerPresenter(ISelectCustomerView view, HttpContextBase httpContext, INydusDataContext dataContext) 
            : base(view, httpContext)
        {
            view.Search += new System.EventHandler(view_Search);
            view.PrevPage += new System.EventHandler(view_PreviousPage);
            view.NextPage += new System.EventHandler(view_NextPage);
            view.ChooseCustomer += new System.EventHandler(view_ChooseCustomer);
        }

        void view_Search(object sender, System.EventArgs e)
        {
            SearchCustomers(0, 10);
        }

        void view_PreviousPage(object sender, System.EventArgs e)
        {
            SearchCustomers(Model.PageNumber-1, 10);
        }

        void view_NextPage(object sender, System.EventArgs e)
        {
            SearchCustomers(Model.PageNumber + 1, 10);
        }
       
        void view_ChooseCustomer(object sender, System.EventArgs e)
        {
            throw new System.NotImplementedException();
        }

        private void SearchCustomers(int pageNumber, int pageSize)
        {
            UnitOfWork uow = new UnitOfWork();
            CustomerRepository repo = new CustomerRepository(uow);

            if (View.Model.Customer.Id >= 0)
            {
                Model.PageNumber = 0;
                Model.CustomerList = new Customer[] { repo.GetById(Model.Customer.Id) };
                
            }
            else
            {
                string customerName = Model.Customer.Name ?? String.Empty;

                Model.PageNumber = pageNumber;
                Model.CustomerList = repo.All
                                        .Where(p => p.Name.ToLower().Contains(customerName.ToLower()))
                                        .Skip(pageNumber * pageSize).Take(pageSize);
            }
        }

        
    }
}